<template>
  <div class="flex flex-col items-center justify-start">
    <img class="logo" src="" alt="" />

    <van-cell-group inset>
      <van-field v-model="form.mobile" label="手机号" placeholder="请输入手机号" />
      <van-field v-model="form.code" center clearable label="短信验证码" placeholder="请输入短信验证码">
        <template #button>
          <div v-if="!showTime" class="send-sms" @click="handleGetSms">发送验证码</div>
          <div v-else class="send-sms sended-sms">{{ countdown }}</div>
        </template>
      </van-field>
    </van-cell-group>

    <div class="login-btn" @click="handleLogin">登录</div>
  </div>
</template>

<script setup lang="ts" name="Login">
import { IForm } from './type'
import { PhoneReg } from '@/utils/validate'
import { showSuccessToast, showFailToast } from 'vant'
import router from '@/router'
import { getSmsApi, postLoginApi } from '@/api/login'
const route = useRoute()

const form: IForm = reactive({
  mobile: '',
  code: '',
})

// 倒计时
const countdown = ref(60)
// 发送验证码 ｜ 倒计时 控制按钮
const showTime = ref(false)

const handleGetSms = async () => {
  if (!form.mobile || !PhoneReg.test(form.mobile)) {
    showFailToast('请输入正确的手机号')
    return
  }
  showTime.value = true
  // 调用接口
  await getSmsApi({ mobile: form.mobile, type: 2 })
  showSuccessToast('发送成功')
  // 定时器
  const timer: number = window.setInterval(() => {
    if (countdown.value === 0) {
      clearInterval(timer)
      countdown.value = 60
      showTime.value = false
      return
    }
    countdown.value -= 1
  }, 1000)
}

// 登录跳转
const handleLogin = async () => {
  if (!form.mobile || !PhoneReg.test(form.mobile)) {
    showFailToast('请输入正确的手机号')
    return
  }
  if (!form.code) {
    showFailToast('请输入验证码')
    return
  }
  // 调用接口
  const { data } = await postLoginApi(form)
  localStorage.setItem('token', data.token)
  router.push({ path: (route.query?.redirect as string) ?? '/' })
}
</script>

<style scoped lang="scss">
.logo {
  width: 100px;
  height: 100px;
  margin: 100px 0 30px;
}

:deep(.van-cell-group),
:deep(.van-cell) {
  background: transparent;
}

.login-btn {
  width: 179px;
  height: 33px;
  background: #212521;
  border-radius: 17px;
  font-size: 14px;
  color: #96ff9b;
  line-height: 33px;
  text-align: center;
  margin: 30px 98px 0;
}

.send-sms {
  text-align: center;
  padding: 0 10px;
  background: #06b4fd;
  color: #fff;
  height: 36px;
  line-height: 36px;
  width: 90px;
}

.sended-sms {
  background: #989898;
}
</style>
